﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ChuanYe.IBLL;
using ChuanYe.Models;
using Microsoft.Practices.Unity;
using ChuanYe.Commom;
using System.Web.Http.Cors;
using SJPlatForm.Web.Models.SMSModel;

namespace SJPlatForm.Web.Controllers
{
    //[Authorize]
    /// <summary>
    /// 短信模块
    /// </summary>
    [EnableCors("*", "*", "*")]
    public class SmsController : BaseApiController
    {
        [Dependency]
        public ISms_SendInfoBLL m_bll { get; set; }
        // GET: Sms
        //public ActionResult SendSms()
        //{
        //    GetSmsPhone();
        //    return View();
        //}


        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="obj">短信内容：SmsInfo,手机号：PhoneInfo 手机号格式：人员姓名，手机号|人员姓名，手机号</param>
        /// <returns></returns>
        // POST actionapi/Sms/CreateSms_SendInfo
        [System.Web.Http.HttpPost]
        public bool CreateSms_SendInfo(dynamic obj)
        {
            bool result = true;
            try
            {
                var context = HttpContext.Current;
                Sms_SendInfo model = new Sms_SendInfo();
                model.IsAchieved = false;
                model.SendDate = DateTime.Now;
                model.SmsInfo = obj.SmsInfo;
                model.Sender = GetLoginInfo(obj.key.ToString()).UserName;
                model.SenderCode = GetLoginInfo(obj.key.ToString()).UserCode;
                model.SafetyCode= Guid.NewGuid().ToString();
                string PhoneInfo = obj.PhoneInfo;
                string[] Phones = PhoneInfo.Split('|');
                foreach (var item in Phones)
                {
                    string[] info = item.Split(',');
                    model.MobileCode = info[1];
                    model.Receiver = info[0];
                    m_bll.CreateSms_SendInfo(model);
                }
                Log.Info(obj.key.ToString(), "短信发送", "短信发送成功！");
            }
            catch (Exception ex) {
                Log.Error("SmsController", ex.ToString());
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 获取所有通讯录
        /// </summary>
        /// <returns></returns>
        // POST actionapi/Sms/GetSmsPhone
        [System.Web.Http.HttpPost]
        public List<GetAllSmsPhoneResult> GetSmsPhone()
        {
            try
            {
                List<ChuanYe.Models.Model.View_SmsPhone> SmsPhones= m_bll.GetSmsPhone();
                List<Departments> AllDepartments= m_bll.GetAllDepartments();
                var result = from d in AllDepartments
                             select new GetAllSmsPhoneResult
                             {
                                 ID = d.ID,
                                 UserName = d.DepName,
                                 Sort = d.Sort,
                                 children = (from p in SmsPhones
                                             where p.DepID == d.ID
                                             select p).ToList()
                             };
                return result.ToList();
            }
            catch (Exception ex)
            {
                Log.Error("SmsController", ex.ToString());
                List<GetAllSmsPhoneResult> result = new List<GetAllSmsPhoneResult>();
                return result;
            }
        }

        /// <summary>
        /// 获取所有通讯录
        /// </summary>
        /// <returns></returns>
        // POST actionapi/Sms/GetSmsPhone
        [System.Web.Http.HttpPost]
        public List<GetAllSmsPhoneResult> GetSmsPhone2()
        {
            try
            {
                List<ChuanYe.Models.Model.View_SmsPhone> SmsPhones = m_bll.GetSmsPhone();
                List<Departments> AllDepartments = m_bll.GetAllDepartments();
                var result = from d in AllDepartments
                             select new GetAllSmsPhoneResult
                             {
                                 ID = d.ID,
                                 UserName = d.DepName,
                                 Sort = d.Sort,
                                 children = (from p in SmsPhones
                                             where p.DepID == d.ID
                                             select p).ToList()
                             };
                return result.ToList();
            }
            catch (Exception ex)
            {
                Log.Error("SmsController", ex.ToString());
                List<GetAllSmsPhoneResult> result = new List<GetAllSmsPhoneResult>();
                return result;
            }
        }




        /// <summary>
        /// 获取所有部门
        /// </summary>
        /// <returns></returns>
        // POST actionapi/Sms/GetAllDepartments
        //[Route("GetSmsPhone")]
        [System.Web.Http.HttpPost]
        public List<Departments> GetAllDepartments()
        {
            try
            {
                return m_bll.GetAllDepartments();
            }
            catch (Exception ex)
            {
                Log.Error("SmsController", ex.ToString());
                List<Departments> result = new List<Departments>();
                return result;
            }
        }

        /// <summary>
        /// 分页查询短信信息
        /// </summary>
        /// <param name="obj">接收人：Receiver，发送时间：SendDate，短信内容：SmsInfo，是否发送：IsAchieved，页数：page，行数：rows</param>
        /// <returns></returns>
        // POST actionapi/Sms/GetSms_SendInfo
        [System.Web.Http.HttpPost]
        public Sms_SendInfoResult GetSms_SendInfo(dynamic obj)
        {
            try
            {
                Sms_SendInfo search = new Sms_SendInfo();
                search.Receiver = obj.Receiver == null ? "" : obj.Receiver.ToString();
                if (obj.SendDate != null&& obj.SendDate !="")
                {
                    search.SendDate = Convert.ToDateTime(obj.SendDate);
                }
                search.SmsInfo = obj.SmsInfo == null ? "" : obj.SmsInfo;
                //search.IsAchieved = obj.IsAchieved;
                int str = obj.IsAchieved;
                switch (str)
                {
                    case 1:
                        search.IsAchieved = true;
                        break;
                    case 0:
                        search.IsAchieved = false;
                        break;
                    case 2:
                        search.IsAchieved = null;
                        break;
                }
                GridPager Pager = new GridPager();
                Pager.page = obj.page == null ? 1 : Convert.ToInt32(obj.page);
                Pager.rows = obj.rows == null ? 10 : Convert.ToInt32(obj.rows);
                return m_bll.GetSms_SendInfo(search, Pager);
            }
            catch (Exception ex) {
                Log.Error("SmsController", ex.ToString());
                Sms_SendInfoResult result = new Sms_SendInfoResult();
                return result;
            }
        }

        /// <summary>
        /// 短信数据多条删除
        /// </summary>
        /// <param name="obj">短信ID：ID 格式：ID|ID</param>
        /// <returns></returns>
        // POST actionapi/Sms/Sms_SendInfoDelete
        [System.Web.Http.HttpPost]
        public int Sms_SendInfoDelete(dynamic obj)
        {
            try
            {
                int result = 0;
                string strID = obj.ID;
                string[] strIDs = strID.Split('|');
                foreach (var item in strIDs)
                {
                    result = result + m_bll.Sms_SendInfoDelete(int.Parse(item));
                }
                if (result > 0)
                {
                    Log.Info(obj.key.ToString(), "短信查询", "短信删除成功！");
                }
                return result;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }
        
        /// <summary>
        /// 获取所有的短信模板
        /// </summary>
        /// <returns></returns>
        // POST actionapi/Sms/GetSMS_Model
        [System.Web.Http.HttpPost]
        public List<SMS_Model> GetSMS_Model()
        {
            try
            {
                return m_bll.GetSMS_Model();
            }
            catch (Exception ex)
            {
                Log.Error("SmsController", ex.ToString());
                List<SMS_Model> result = new List<SMS_Model>();
                return result;
            }
        }

        /// <summary>
        /// 添加短信模板
        /// </summary>
        /// <param name="obj">短信模板内容：Mcont 模版类型:MType</param>
        /// <returns></returns>
        // POST actionapi/Sms/CreateSMS_Model
        [System.Web.Http.HttpPost]
        public bool CreateSMS_Model(dynamic obj)
        {
            try
            {
                SMS_Model model = new SMS_Model();
                //model.SMS_Mtitle = Request["Mtitle"];
                model.SMS_Mcont = obj.Mcont;
                var context = HttpContext.Current;
                model.SMS_MTransUser = GetLoginInfo(obj.key.ToString()).UserCode;
                model.SMS_MTransDatetime = DateTime.Now;
                model.SMS_MType =Convert.ToInt32(obj.MType);
                //model.SMS_MTransIP = Request.ServerVariables.Get("Remote_Addr").ToString();
                #region 获取客户端IP
                string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (string.IsNullOrEmpty(result))
                {
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                if (string.IsNullOrEmpty(result))
                {
                    result = HttpContext.Current.Request.UserHostAddress;
                }
                if (string.IsNullOrEmpty(result))
                {
                    result = "0.0.0.0";
                }
                model.SMS_MTransIP = result;
                #endregion
                bool RT= m_bll.CreateSMS_Model(model);
                if (RT)
                {
                    Log.Info(obj.key.ToString(), "短信模板", "短信模板添加成功！");
                }
                return RT;
            }
            catch (Exception ex) {
                Log.Error("SmsController", ex.ToString());
                return false;
            }
        }

        /// <summary>
        /// 添加或修改短信模板
        /// </summary>
        /// <param name="obj">短信模板ID:SMS_MID，短信模板内容:Mcont  模版类型:MType</param>
        /// <returns></returns>
        // POST actionapi/Sms/CreateSMS_Model
        [System.Web.Http.HttpPost]
        public bool CreateOrUpdateSMS_Model(dynamic obj)
        {
            try
            {
                string SMS_MID = obj.SMS_MID==null?"": obj.SMS_MID;
                if (SMS_MID == "")
                {
                    SMS_Model model = new SMS_Model();
                    //model.SMS_Mtitle = Request["Mtitle"];
                    model.SMS_Mcont = obj.Mcont;
                    model.SMS_MTransUser = GetLoginInfo(obj.key.ToString()).UserCode;
                    model.SMS_MTransDatetime = DateTime.Now;
                    model.SMS_MType = obj.MType == null ? 0 : Convert.ToInt32(obj.MType);
                    #region 获取客户端IP
                    string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    if (string.IsNullOrEmpty(result))
                    {
                        result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                    }
                    if (string.IsNullOrEmpty(result))
                    {
                        result = HttpContext.Current.Request.UserHostAddress;
                    }
                    if (string.IsNullOrEmpty(result))
                    {
                        result = "0.0.0.0";
                    }
                    model.SMS_MTransIP = result;
                    #endregion
                    Log.Info(obj.key.ToString(), "短信模板", "短信模板添加成功！");
                    return m_bll.CreateSMS_Model(model);
                }
                else {
                    SMS_Model model = new SMS_Model();
                    model.SMS_MID = Convert.ToInt32(obj.SMS_MID);
                    model.SMS_Mcont = obj.Mcont;
                    model.SMS_MType = obj.MType == null ? 0 : Convert.ToInt32(obj.MType);
                    bool RT= m_bll.SMS_ModelUpdate(model) > 0 ? true : false;
                    if (RT)
                    {
                        Log.Info(obj.key.ToString(), "短信模板", "短信模板修改成功！");
                    }
                    return RT;
                }
            }
            catch (Exception ex)
            {
                Log.Error("SmsController", ex.ToString());
                return false;
            }
        }

        /// <summary>
        /// 删除短信模板
        /// </summary>
        /// <param name="obj">短信模板ID:ID</param>
        /// <returns></returns>
        // POST actionapi/Sms/SMS_ModelDelete
        [System.Web.Http.HttpPost]
        public int SMS_ModelDelete(dynamic obj)
        {
            try
            {
                int RT = m_bll.SMS_ModelDelete(Convert.ToInt32(obj.ID));
                if (RT > 0)
                {
                    Log.Info(obj.key.ToString(), "短信模板", "短信模板删除成功！");
                }
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("SmsController", ex.ToString());
                return -1;
            }
        }

        /// <summary>
        ///根据ID获取短信模板
        /// </summary>
        /// <param name="obj">短信模板ID:ID</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public SMS_Model GetSMS_ModelByID(dynamic obj)
        {
            try
            {
                return m_bll.GetSMS_ModelByID(Convert.ToInt32(obj.ID));
            }
            catch (Exception ex)
            {
                Log.Error("SmsController", ex.ToString());
                SMS_Model result = new SMS_Model();
                return result;
            }
        }

        /// <summary>
        /// 修改短信模板
        /// </summary>
        /// <param name="obj">短信模板ID：SMS_MID，短信模板内容：Mcont</param>
        /// <returns></returns>
        // POST actionapi/Sms/SMS_ModelUpdate
        [System.Web.Http.HttpPost]
        public int SMS_ModelUpdate(dynamic obj)
        {
            try
            {
                SMS_Model model = new SMS_Model();
                model.SMS_MID = Convert.ToInt32(obj.SMS_MID);
                //model.SMS_Mtitle = Request["Mtitle"];
                model.SMS_Mcont = obj.Mcont;
                int RT= m_bll.SMS_ModelUpdate(model);
                if (RT > 0)
                {
                    Log.Info(obj.key.ToString(), "短信模板", "短信模板修改成功！");
                }
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("SmsController", ex.ToString());
                return -1;
            }
        }
        
        /// <summary>
        /// 分页查询短信模板
        /// </summary>
        /// <param name="obj">短信模板内容：Mcont，页数：page，行数：rows</param>
        /// <returns></returns>
        // POST actionapi/Sms/SearchSMS_Model
        [System.Web.Http.HttpPost]
        public SMS_ModelResult SearchSMS_Model(SMSSearchReq obj)
        {
            try
            {
                GridPager Pager = new GridPager();
                Pager.page =obj.page;
                Pager.rows = obj.rows;
                return m_bll.GetSMS_Model(obj.Mcont,obj.MType, Pager);
            }
            catch (Exception ex)
            {
                Log.Error("SmsController", ex.ToString());
                return new SMS_ModelResult();
            }
        }



        public string Options()
        {
            return null; // HTTP 200 response with empty body
        }
    }
}